<template>
  <div 
    class="floating-gauge" 
    :class="{ 'collapsed': isCollapsed }"
    :style="gaugePosition"
    @mousedown="startDrag"
  >
    <!-- 折叠按钮 -->
    <div class="gauge-header">
      <div class="title" v-if="!isCollapsed">
        <span>情绪风险监测</span>
        <el-tooltip content="实时监测对话中的情绪风险">
          <el-icon><InfoFilled /></el-icon>
        </el-tooltip>
      </div>
      <el-button
        class="collapse-btn"
        :icon="isCollapsed ? Expand : Fold"
        circle
        size="small"
        @click.stop="toggleCollapse"
      />
    </div>

    <!-- 饼图内容 -->
    <div class="gauge-content" v-show="!isCollapsed">
      <div class="pie-container">
        <div class="pie-chart">
          <div class="pie" :style="pieStyle">
            <transition name="fade">
              <div class="pie-value" :style="pieValueStyle"></div>
            </transition>
          </div>
          <div class="pie-center">
            <transition name="fade">
              <div class="risk-level">{{ currentLevel }}</div>
            </transition>
            <transition name="fade">
              <div class="risk-score">{{ (value * 100).toFixed(0) }}%</div>
            </transition>
          </div>
        </div>
        <div class="gauge-labels">
          <span class="label low">低风险</span>
          <span class="label medium">中风险</span>
          <span class="label high">高风险</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { InfoFilled, Expand, Fold } from '@element-plus/icons-vue'

const props = defineProps<{
  value: number,
  trend?: number[] // 添加趋势数据属性
}>()

const isCollapsed = ref(false)
const position = ref({
  x: window.innerWidth - 400, // 左移一些，留出更多空间
  y: 180 // 下移一些，避免遮挡顶部内容
})
let isDragging = false
let dragOffset = { x: 0, y: 0 }

// 获取折叠按钮的垂直中心位置
const getChatMiddleY = () => {
  return Math.max(window.innerHeight / 2 - 20, 0)
}

// 修改位置计算逻辑
const gaugePosition = computed(() => {
  if (isCollapsed.value) {
    // 折叠时固定在右侧中间
    return {
      right: '20px',
      top: `${getChatMiddleY()}px`,
      left: 'auto',
      transform: 'translateY(-50%)'
    }
  }
  
  // 展开时跟随拖动位置
  return {
    left: `${position.value.x}px`,
    top: `${position.value.y}px`,
    right: 'auto',
    transform: 'none'
  }
})

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  if (!isCollapsed.value) {
    // 展开时恢复到默认位置
    position.value = {
      x: window.innerWidth - 320,
      y: 180
    }
  }
}

const startDrag = (e: MouseEvent) => {
  // 折叠状态或点击折叠按钮时不启动拖动
  if (isCollapsed.value || (e.target as HTMLElement).closest('.collapse-btn')) return
  
  isDragging = true
  dragOffset.x = e.clientX - position.value.x
  dragOffset.y = e.clientY - position.value.y
  
  // 添加拖动时的样式
  const gauge = e.currentTarget as HTMLElement
  gauge.style.transition = 'none'
  gauge.style.cursor = 'grabbing'
  
  window.addEventListener('mousemove', onDrag)
  window.addEventListener('mouseup', stopDrag)
}

const onDrag = (e: MouseEvent) => {
  if (!isDragging) return
  
  requestAnimationFrame(() => {
    position.value = {
      x: Math.min(Math.max(0, e.clientX - dragOffset.x), window.innerWidth - 220),
      y: Math.min(Math.max(60, e.clientY - dragOffset.y), window.innerHeight - 160)
    }
  })
}

const stopDrag = () => {
  if (!isDragging) return
  
  isDragging = false
  // 恢复过渡动画
  const gauge = document.querySelector('.floating-gauge') as HTMLElement
  if (gauge) {
    gauge.style.transition = ''
    gauge.style.cursor = 'move'
  }
  
  window.removeEventListener('mousemove', onDrag)
  window.removeEventListener('mouseup', stopDrag)
}

const currentLevel = computed(() => {
  const value = props.value
  if (value < 0.4) return '低风险'
  if (value < 0.7) return '中风险'
  return '高风险'
})

const pieValueStyle = computed(() => {
  return {
    transform: `scaleY(${props.value})`,
    transition: 'transform 0.5s ease-in-out',
    backgroundColor: getRiskColor(props.value)
  }
})

const pieStyle = computed(() => {
  const color = props.value >= 0.7 ? '#f44336' : 
                props.value >= 0.4 ? '#ffc107' : '#4caf50'
  return {
    backgroundColor: color
  }
})

// 根据风险值获取颜色
const getRiskColor = (value: number) => {
  if (value < 0.4) return '#4caf50'      // 低风险 - 绿色
  if (value < 0.7) return '#ffc107'      // 中风险 - 黄色
  return '#f44336'                        // 高风险 - 红色
}

// 添加值变化的动画效果
watch(() => props.value, (newValue, oldValue) => {
  if (oldValue !== undefined) {
    // 添加过渡动画类
    const element = document.querySelector('.pie-value')
    if (element) {
      element.classList.add('value-change')
      setTimeout(() => {
        element.classList.remove('value-change')
      }, 500)
    }
  }
})
</script>

<style lang="scss" scoped>
.floating-gauge {
  position: fixed;
  z-index: 1000;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  width: 200px;
  cursor: move;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform;
  
  &.collapsed {
    position: fixed;
    width: auto;
    background: transparent;
    box-shadow: none;
    cursor: default;
    
    .gauge-header {
      background: transparent;
      padding: 0;
      border: none;
      
      .collapse-btn {
        position: relative;
        z-index: 1001;
        background-color: #fff;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
        transition: all 0.3s ease;
        
        &:hover {
          background-color: #f5f7fa;
          transform: scale(1.1);
        }
      }
    }
  }

  .gauge-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background: #f8f9fa;
    border-bottom: 1px solid #dcdfe6;
    border-radius: 8px 8px 0 0;

    .title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      font-weight: 500;
      color: #606266;

      .el-icon {
        color: #909399;
        cursor: help;
      }
    }

    .collapse-btn {
      cursor: pointer;
    }
  }

  .gauge-content {
    padding: 15px;
  }

  .pie-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }

  .pie-chart {
    position: relative;
    width: 120px;
    height: 120px;
  }

  .pie {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    position: relative;
    overflow: hidden;
    background: #e0e0e0;
    
    .pie-value {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: inherit;
      transform-origin: 50% 50%;
      transition: all 0.5s ease-in-out;
      
      &.value-change {
        animation: pulse 0.5s ease-in-out;
      }
    }
  }

  .pie-center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80px;
    height: 80px;
    background: white;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    box-shadow: inset 0 0 8px rgba(0,0,0,0.1);

    .risk-level {
      font-size: 14px;
      font-weight: bold;
      color: #333;
    }

    .risk-score {
      font-size: 12px;
      color: #666;
      margin-top: 4px;
    }
  }

  .gauge-labels {
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 0 10px;

    .label {
      font-size: 12px;
      &.low { color: #4caf50; }
      &.medium { color: #ffc107; }
      &.high { color: #f44336; }
    }
  }
}

// 添加动画关键帧
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

// 淡入淡出过渡
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
